#!/bin/bash
###
 # @Author: Loganli
 # @Gitee: https://gitee.com/attacker
 # @email: admin@attacker.club
 # @Date: 2025-04-25 14:35:00
 # @Description: 通用Zabbix Agent 7.2安装脚本（支持CentOS 7/8、Ubuntu、AWS Linux 2/3）
 # curl -s https://gitee.com/attacker/deploy-zabbix/raw/master/agent/zabbix-agent-universal.sh | bash -s <zabbix_server_ip> <hostname> [active|agent] [binary]
 # curl -s [https://gitee.com/attacker/deploy-zabbix/raw/master/agent/zabbix-agent-universal.sh](https://gitee.com/attacker/deploy-zabbix/raw/master/agent/zabbix-agent-universal.sh) | bash -s 10.0.0.102 pro-sql agent binary
###
###

# 终端颜色设置
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m' # 恢复默认

# 定义函数：彩色输出
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[成功]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[警告]${NC} $1"
}

log_error() {
    echo -e "${RED}[错误]${NC} $1"
}

# 检查参数
ZBX_SERVER=$1  # zabbix服务器地址
HOSTNAME=$2   # 主机名称
mode=${3:-"agent"}  # 默认被动模式
install_method=${4:-"repo"}  # 默认使用仓库安装，可选"binary"使用二进制包

log_info "开始安装Zabbix Agent 7.2..."
log_info "服务器IP: ${BOLD}$ZBX_SERVER${NC}"
log_info "主机名: ${BOLD}$HOSTNAME${NC}"
log_info "模式: ${BOLD}$mode${NC}"
log_info "安装方式: ${BOLD}$install_method${NC}"

# 停止现有服务
systemctl stop zabbix-agent 2>/dev/null || service zabbix-agent stop 2>/dev/null || true

# 检测操作系统
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
    VERSION=$VERSION_ID
    log_info "检测到操作系统: ${BOLD}$PRETTY_NAME${NC}"
else
    log_error "无法检测操作系统类型！"
    exit 1
fi

# 设置主机名
log_info "设置主机名: $HOSTNAME"
if [ -f /etc/hostname ]; then
    echo "$HOSTNAME" > /etc/hostname
fi
hostname $HOSTNAME
grep -q "$HOSTNAME" /etc/hosts || echo "127.0.0.1 $HOSTNAME" >> /etc/hosts

# 定义使用静态二进制包安装的函数
install_binary_package() {
    log_info "使用静态二进制包安装Zabbix Agent 7.2..."
    
    # 停止现有服务
    log_info "停止现有Zabbix Agent服务..."
    systemctl stop zabbix-agent 2>/dev/null || service zabbix-agent stop 2>/dev/null || true
    killall zabbix_agentd 2>/dev/null || true
    
    # 清理现有安装
    log_info "清理现有安装..."
    rm -rf /opt/zabbix
    mkdir -p /opt/zabbix/{sbin,bin,etc,var/run}
    mkdir -p /var/log/zabbix
    mkdir -p /etc/zabbix/zabbix_agentd.d
    
    # 下载静态二进制包
    cd $(mktemp -d)
    TEMP_DIR=$PWD
    log_info "下载Zabbix Agent 7.2.4静态二进制包..."
    curl -fsSL -O --max-time 60 --retry 3 --retry-delay 10 https://cdn.zabbix.com/zabbix/binaries/stable/7.2/7.2.4/zabbix_agent-7.2.4-linux-3.0-amd64-static.tar.gz
    
    if [ ! -f zabbix_agent-7.2.4-linux-3.0-amd64-static.tar.gz ]; then
        log_error "下载失败！请检查网络连接和URL"
        exit 1
    fi
    
    # 解压并显示目录结构
    log_info "解压安装包..."
    mkdir -p extract-temp
    tar -xzf zabbix_agent-7.2.4-linux-3.0-amd64-static.tar.gz -C extract-temp
    ls -la extract-temp
    
    # 查找二进制文件并复制
    log_info "安装二进制文件..."
    find extract-temp -name "zabbix_agentd" -type f -exec cp -v {} /opt/zabbix/sbin/ \;
    find extract-temp -name "zabbix_get" -type f -exec cp -v {} /opt/zabbix/bin/ \; 2>/dev/null || true
    find extract-temp -name "zabbix_sender" -type f -exec cp -v {} /opt/zabbix/bin/ \; 2>/dev/null || true
    
    # 设置执行权限
    chmod +x /opt/zabbix/sbin/zabbix_agentd
    chmod +x /opt/zabbix/bin/zabbix_get 2>/dev/null || true
    chmod +x /opt/zabbix/bin/zabbix_sender 2>/dev/null || true
    
    # 创建符号链接
    ln -sf /opt/zabbix/sbin/zabbix_agentd /usr/sbin/zabbix_agentd
    ln -sf /opt/zabbix/bin/zabbix_get /usr/bin/zabbix_get 2>/dev/null || true
    ln -sf /opt/zabbix/bin/zabbix_sender /usr/bin/zabbix_sender 2>/dev/null || true
    ln -sf /opt/zabbix/etc /etc/zabbix
    
    return 0
}

install_for_rhel_based() {
    local version=$1
    local arch="x86_64"
    
    log_info "添加Zabbix官方仓库..."
    if [ "$version" == "7" ]; then
        log_info "使用RHEL/CentOS 7专用Zabbix 7.2仓库..."
        rpm -Uvh https://repo.zabbix.com/zabbix/7.2/release/rhel/7/noarch/zabbix-release-latest-7.2.el7.noarch.rpm
    elif [ "$version" == "8" ]; then
        log_info "使用CentOS 8专用Zabbix 7.2仓库..."
        rpm -Uvh https://repo.zabbix.com/zabbix/7.2/release/centos/8/noarch/zabbix-release-latest-7.2.el8.noarch.rpm
    elif [ "$version" == "9" ]; then
        rpm -Uvh https://repo.zabbix.com/zabbix/7.0/rhel/9/x86_64/zabbix-release-7.0-1.el9.noarch.rpm
    else
        log_warning "未知的RHEL版本: $version，尝试使用EL8仓库..."
        rpm -Uvh https://repo.zabbix.com/zabbix/7.0/rhel/8/x86_64/zabbix-release-7.0-1.el8.noarch.rpm
    fi
    
    if command -v dnf &>/dev/null; then
        log_info "使用DNF包管理器..."
        dnf clean all
        dnf makecache
        dnf install -y zabbix-agent
    else
        log_info "使用YUM包管理器..."
        yum clean all
        yum makecache fast
        yum install -y --debuglevel=1 zabbix-agent
    fi
}

install_for_debian_based() {
    local codename=$1
    local version=$2
    
    log_info "添加Zabbix官方仓库..."
    
    # 对于Ubuntu 24.04使用专用包
    if [ "$OS" = "ubuntu" ] && [ "$version" = "24.04" ]; then
        log_info "检测到Ubuntu 24.04，使用专用仓库包..."
        wget -q https://repo.zabbix.com/zabbix/7.2/release/ubuntu/pool/main/z/zabbix-release/zabbix-release_latest_7.2+ubuntu24.04_all.deb
        dpkg -i zabbix-release_latest_7.2+ubuntu24.04_all.deb
    else
        # 旧方法，适用于其他Ubuntu/Debian版本
        apt-get update
        apt-get install -y ca-certificates apt-transport-https gnupg
        
        # 添加Zabbix仓库
        wget -q -O - https://repo.zabbix.com/zabbix-official-repo.key | apt-key add -
        echo "deb https://repo.zabbix.com/zabbix/7.0/ubuntu $codename main contrib non-free" > /etc/apt/sources.list.d/zabbix.list
    fi
    
    # 安装Zabbix Agent
    apt-get update
    apt-get install -y zabbix-agent
}

# 根据操作系统安装Zabbix Agent
if [ "$install_method" == "binary" ]; then
    # 使用静态二进制包安装
    install_binary_package
else
    # 使用仓库安装
    case $OS in
        centos|rhel|rocky|almalinux)
            install_for_rhel_based ${VERSION%%.*}
            ;;
        amzn)
            if [ "$VERSION" == "2" ]; then
                log_info "检测到AWS Linux 2"
                install_for_rhel_based 7
            else
                log_info "检测到AWS Linux 2023"
                # 使用官方 Amazon Linux 2023 专用仓库
                log_info "添加官方Amazon Linux 2023专用Zabbix仓库..."
                rpm -Uvh https://repo.zabbix.com/zabbix/7.2/release/amazonlinux/2023/noarch/zabbix-release-latest-7.2.amzn2023.noarch.rpm
                
                log_info "使用DNF包管理器..."
                dnf clean all
                dnf makecache
                
                # 安装额外的依赖
                log_info "安装所需依赖..."
                dnf install -y openldap-compat || true
                
                dnf install -y zabbix-agent
                
                # Amazon Linux 2023专用修复：使用特殊的systemd服务配置
                log_info "为Amazon Linux 2023创建特殊的systemd服务配置..."
                cat > /etc/systemd/system/zabbix-agent.service << EOF
[Unit]
Description=Zabbix Agent
After=network.target

[Service]
Type=simple
User=zabbix
ExecStart=/usr/sbin/zabbix_agentd -f -c /etc/zabbix/zabbix_agentd.conf
Restart=on-failure
KillMode=process
RestartSec=10s
LimitNOFILE=10000
TimeoutStartSec=30

[Install]
WantedBy=multi-user.target
EOF
                systemctl daemon-reload
            fi
            ;;
        ubuntu|debian)
            install_for_debian_based $VERSION_CODENAME $VERSION_ID
            ;;
        *)
            log_error "不支持的操作系统: $OS"
            exit 1
            ;;
    esac
fi

# 备份原始配置
if [ -f /etc/zabbix/zabbix_agentd.conf ]; then
    cp /etc/zabbix/zabbix_agentd.conf /etc/zabbix/zabbix_agentd.conf.orig
fi

# 获取PID文件和日志文件的位置
if [ "$OS" = "ubuntu" ] || [ "$OS" = "debian" ]; then
    PID_FILE="/run/zabbix/zabbix_agentd.pid"
    LOG_FILE="/var/log/zabbix/zabbix_agentd.log"
else
    PID_FILE="/run/zabbix/zabbix_agentd.pid"
    LOG_FILE="/var/log/zabbix/zabbix_agentd.log"
fi

# 配置Zabbix Agent
log_info "配置Zabbix Agent..."
cat > /etc/zabbix/zabbix_agentd.conf << EOF
PidFile=$PID_FILE
LogFile=$LOG_FILE
LogFileSize=0
Server=${ZBX_SERVER}
ServerActive=${ZBX_SERVER}
Hostname=$HOSTNAME
HostMetadata=Linux
EnableRemoteCommands=1
Timeout=30
Include=/etc/zabbix/zabbix_agentd.d/*.conf
EOF

# 根据模式调整配置
if [ "$mode" == "active" ]; then
    log_info "配置为主动模式..."
    sed -i '/Server=/d' /etc/zabbix/zabbix_agentd.conf
    sed -i '4a StartAgents=0' /etc/zabbix/zabbix_agentd.conf
fi

# 创建zabbix_agentd.d目录（如果不存在）
mkdir -p /etc/zabbix/zabbix_agentd.d

# 下载额外的监控配置
log_info "下载额外监控配置..."
cd $(mktemp -d)
curl -fsSL -O --max-time 30 --retry 3 http://wuyou.run/scripts/monitor/zabbix/zabbix-agent/zabbix_agentd.d.tar.gz

if [ -f zabbix_agentd.d.tar.gz ]; then
    tar zxvf zabbix_agentd.d.tar.gz -C /etc/zabbix/zabbix_agentd.d/ --strip-components 1
    log_success "已安装额外的监控配置"
else
    log_warning "额外配置文件下载失败，将使用基本配置"
fi

# 更新权限
if id -u zabbix >/dev/null 2>&1; then
    chown -R zabbix:zabbix /etc/zabbix/zabbix_agentd.d/ 2>/dev/null || true
fi

# 启动并启用服务
log_info "启动Zabbix Agent服务..."
systemctl enable zabbix-agent || update-rc.d zabbix-agent enable
systemctl restart zabbix-agent || service zabbix-agent restart

# 等待服务启动
sleep 2

# 检查进程是否运行
zabbix_process=$(ps aux | grep zabbix_agentd | grep -v grep)

if [ -z "$zabbix_process" ]; then
    log_error "Zabbix Agent未运行，查看日志..."
    
    if [ -f "$LOG_FILE" ]; then
        tail -n 20 "$LOG_FILE"
    fi
    
    journalctl -u zabbix-agent --no-pager -n 20 2>/dev/null || true
    
    log_info "尝试直接启动Agent以检查问题..."
    /usr/sbin/zabbix_agentd -c /etc/zabbix/zabbix_agentd.conf -f
else
    log_success "Zabbix Agent 7.2 安装成功并正在运行！"
    echo "进程信息(主要进程):"
    echo "$zabbix_process" |grep -v listener | head -3
    
    log_info "主机名: ${BOLD}$HOSTNAME${NC}"
    log_info "服务器: ${BOLD}$ZBX_SERVER${NC}"
    log_info "运行模式: ${BOLD}$mode${NC}"
    
    # 尝试获取版本信息
    if command -v zabbix_agentd &>/dev/null; then
        agent_version=$(zabbix_agentd -V | head -n 1)
        log_info "Agent版本: ${BOLD}$agent_version${NC}"
    fi
fi

# 安装完成后的清理工作
log_info "清理工作目录..."
# 不使用变量删除，明确指定删除临时文件
[ -d /tmp/zabbix_tmp ] && rm -rf /tmp/zabbix_tmp

log_info "安装过程完成"
